import { lazy, Suspense } from 'react'
import { Navigate, useLocation } from 'react-router-dom' // 导入导航组件
import { getPremissionRoutes as getPremissionRoutesApi } from '@/store/modules/userStore'
import App from '../App'
import { Spin } from 'antd';
import { useDispatch, useSelector } from 'react-redux'
// React 组件懒加载
const lazyLoad = (moduleName: string) => {
  const Module = lazy(() => import(/* @vite-ignore */`../pages/${moduleName}`)) // 动态导入模块
  // Suspense 路由加载会有等待 配置等待的空白页面
  return <Suspense fallback={<Spin></Spin>}><Module /></Suspense>  // 返回懒加载的模块组件
}
const whiteList = ['/login']
// 路由鉴权组件
const Appraisal = ({ children }: { children: React.ReactNode }) => {
  const { TOKEN } = useSelector((state: RootState) => state.user)
  const { pathname } = useLocation();
  const dispatch: AppDispatch = useDispatch()
  if (TOKEN !== '') {
    return children
  } else {
    return whiteList.includes(pathname) ? children : <Navigate to="/login" />
  }
  // 如果有 token 则渲染子组件，否则跳转到登录页面
}

export const routes: RouteObject[] = [
  {
    path: '/',
    element: <Appraisal><App></App></Appraisal>,
    children: [],
  }, {
    path: '/login',
    element: <Appraisal>{lazyLoad('login')}</Appraisal>, // 懒加载未找到页面组件
  }, {
    path: '/noFound',
    element: <Appraisal>{lazyLoad('noFound')}</Appraisal>, // 懒加载未找到页面组件
  }, {
    path: '*',
    element: <Navigate to={'/noFound'}></Navigate>
  }
]
export const premissionRoutes: RouteObject[] = [
  {
    path: '',
    element: <Appraisal>{lazyLoad('/codeBlock/index')}</Appraisal>, // 默认跳转到 home 页面 
  }, {
    path: '/useState',
    element: <Appraisal>{lazyLoad('HookPages/useState/index')}</Appraisal>, //  useState 页面
  }, {
    path: '/useReducer',
    element: <Appraisal>{lazyLoad('HookPages/useReducer/index')}</Appraisal>, //  useReducer 页面
  },
  {
    path: '/useContext',
    element: <Appraisal>{lazyLoad('HookPages/useContext/index')}</Appraisal>, //  useState 页面
  }, {
    path: '/useMemo',
    element: <Appraisal>{lazyLoad('HookPages/memo/index')}</Appraisal>, //  useState 页面
  }, {
    path: '/useTransition',
    element: <Appraisal>{lazyLoad('HookPages/useTransition/index')}</Appraisal>, //  useTransition 页面
  }, {
    path: '/useDeferredValue',
    element: <Appraisal>{lazyLoad('HookPages/useDeferredValue/index')}</Appraisal>, //  useDeferredValue 页面
  }, {
    path: '/ReduxPage',
    element: <Appraisal>{lazyLoad('ReduxPage/index')}</Appraisal>, //  useDeferredValue 页面
  }
]
